/**
 * 
 */
package com.cgbsoft.financial.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import android.os.Environment;
import android.util.Log;

import com.cgbsoft.financial.FinancialActivity;
import com.cgbsoft.financial.domain.MyTransaction;
import com.cgbsoft.financial.utils.XMLContentHandler;

/**
 * @author CX
 *
 */
public class TransactionFileManager {

	public static final String TAG = "TransactionDBmanager";
	
	public static String TRANSACTION_FILE_PATH = Environment.getExternalStorageDirectory() + "/data/financial/financial.xml";
	
	/**
	 * 保存记录
	 * @param newTransaction
	 * @return
	 */
	public static boolean saveTransaction(final MyTransaction newTransaction) {
		boolean isSuccess = true;
		SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new File(TransactionFileManager.TRANSACTION_FILE_PATH));

            //在DataSet1元素中增加MyTransaction元素
            List list = document.selectNodes("/DataSet1");
            Iterator itr = list.iterator();
            if(itr.hasNext()) {
                Element dataSet1Element = (Element)itr.next();
                Element myTransactionElement = dataSet1Element.addElement("MyTransaction");
                
                Element idElement = myTransactionElement.addElement("ID");
                idElement.setText(String.valueOf(FinancialActivity.lastTransactionId + 1));

                Element dDateElement = myTransactionElement.addElement("d_Date");
                dDateElement.setText(newTransaction.getdDate());
                
                Element iSumElement = myTransactionElement.addElement("i_Sum");
                iSumElement.setText(newTransaction.getiSum());
                
                Element sSubjectElement = myTransactionElement.addElement("s_Subject");
                sSubjectElement.setText(newTransaction.getsSubject());
            }
            
            //输出
            XMLWriter output;
            OutputFormat format = OutputFormat.createPrettyPrint();
            output = new XMLWriter(new FileWriter(TransactionFileManager.TRANSACTION_FILE_PATH), format);
            output.write(document);
            output.close();
        } catch (Exception e) {   
        	isSuccess = false;
            e.printStackTrace();
        }
        return isSuccess;
	}
	
	/**
	 * 根据Id查找transaction
	 * @param transactionId
	 * @return
	 */
	public static boolean modifyTransaction(MyTransaction myTransaction) {
		boolean isSuccess = false;
		
		SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new File(TransactionFileManager.TRANSACTION_FILE_PATH));

            //在DataSet1元素中增加MyTransaction元素
            List list = document.selectNodes("/DataSet1");
            Iterator itr = list.iterator();
            if(itr.hasNext()) {
                Element dataSet1Element = (Element)itr.next();
                List myTransactionElementList = dataSet1Element.elements();
                Iterator myTransactionElementListIterator = myTransactionElementList.iterator();
                while (myTransactionElementListIterator.hasNext()) {
                	Element transactionElement = (Element)myTransactionElementListIterator.next();
                	Element id = transactionElement.element("ID");
                	if (id.getText().equalsIgnoreCase(String.valueOf(myTransaction.getId()))) {
                		//找到本节点，修改节点内容
                		Element d_Date = transactionElement.element("d_Date");
                		d_Date.setText(myTransaction.getdDate());
                		
                		Element i_Sum = transactionElement.element("i_Sum");
                		i_Sum.setText(myTransaction.getiSum());
                		
                		Element s_Subject = transactionElement.element("s_Subject");
                		s_Subject.setText(myTransaction.getsSubject());
                		
                		Element c_Catagory = transactionElement.element("c_Catagory");
                		c_Catagory.setText(myTransaction.getcCatagory());
                		
                		isSuccess = true;
                		break;
                	}
                }
            }
            Log.i(TAG, "isSuccess:" + isSuccess);
            if (isSuccess) {//成功修改内容，保存到xml中
            	//输出
                XMLWriter output;
                OutputFormat format = OutputFormat.createPrettyPrint();
                output = new XMLWriter(new FileWriter(TransactionFileManager.TRANSACTION_FILE_PATH), format);
                output.write(document);
                output.close();
            }
        } catch (Exception e) {  
        	isSuccess = false;
            e.printStackTrace();
        }
		
		return isSuccess;
	}
	
	/**
	 * @param transactionId
	 * @return
	 */
	public static boolean deleteTransaction(String transactionId) {
		boolean isSuccess = false;
		
		SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new File(TransactionFileManager.TRANSACTION_FILE_PATH));

            //在DataSet1元素中增加MyTransaction元素
            List list = document.selectNodes("/DataSet1");
            Iterator itr = list.iterator();
            if(itr.hasNext()) {
                Element dataSet1Element = (Element)itr.next();
                List myTransactionElementList = dataSet1Element.elements();
                Iterator myTransactionElementListIterator = myTransactionElementList.iterator();
                while (myTransactionElementListIterator.hasNext()) {
                	Element transactionElement = (Element)myTransactionElementListIterator.next();
                	Element id = transactionElement.element("ID");
                	if (id.getText().equalsIgnoreCase(transactionId)) {
                		Log.i(TAG, "delectNote:"+id.getText());
                		//找到本节点，删除本节点
                		dataSet1Element.remove(transactionElement);
                		isSuccess = true;
                		break;
                	}
                }
            }
            Log.i(TAG, "isSuccess:" + isSuccess);
            if (isSuccess) {//成功修改内容，保存到xml中
            	//输出
                XMLWriter output;
                OutputFormat format = OutputFormat.createPrettyPrint();
                output = new XMLWriter(new FileWriter(TransactionFileManager.TRANSACTION_FILE_PATH), format);
                output.write(document);
                output.close();
            }
        } catch (Exception e) {  
        	isSuccess = false;
            e.printStackTrace();
        }
		
		return isSuccess;
	}
	
	public static List<MyTransaction> readXML(String transactionFilePath) {
		List<MyTransaction> transactionList = new ArrayList<MyTransaction>();
		try {
			File file = new File(transactionFilePath);
	    	if (!file.exists()) {//如果文件不存在，创建一个
				createEmptyXmlFile(file);
	    	}
			InputStream inStream = new FileInputStream(file);
			
	    	try {
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser saxParser = spf.newSAXParser(); //创建解析器
				XMLContentHandler handler = new XMLContentHandler();
				saxParser.parse(inStream, handler);
				inStream.close();
				transactionList = handler.getMyTransactions();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		return transactionList;
	}
	
	/**
	 * 创建一个新的xml文件
	 * @throws IOException 
	 */
	public static void createEmptyXmlFile(File file) {
		String emtpyXmlRootStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<DataSet1 xmlns=\"http://tempuri.org/DataSet1.xsd\">\n\n</DataSet1>\n";
		try {
			String filePath = file.getAbsolutePath();
			filePath = filePath.substring(0, filePath.lastIndexOf("/"));
			Log.i("", "filePath:" + filePath);
			File dir = new File(filePath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			if (dir.exists()) {
				file.createNewFile();
				OutputStream os = new FileOutputStream(file);
				os.write(emtpyXmlRootStr.getBytes());
				os.flush();
				os.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
